import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_demo/constants/constants.dart';
import 'package:flutter_app_demo/utils/NetUtils.dart';
import 'package:flutter_app_demo/utils/data_utils.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class LoginWebPage extends StatefulWidget {
  @override
  _LoginWebPageState createState() => _LoginWebPageState();
}

class _LoginWebPageState extends State<LoginWebPage> {
  FlutterWebviewPlugin _flutterWebviewPlugin = FlutterWebviewPlugin();

  bool isLoading = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    //监听Url
    _flutterWebviewPlugin.onUrlChanged.listen((url) {
      //LoginWebPage url= https://www.oschina.net/action/oauth2/authorize?response_type=code&client_id=WoCIqX31djQFGKKxh4o1&client_secret=fPHwvUWSXNWpjELiodaKkpweoiA5TPPE&redirect_uri=https://blog.csdn.net/yuzhangzhen
      //LoginWebPage url= https://blog.csdn.net/yuzhangzhen?code=sTXiae&state=c
      print("LoginWebPage url= $url");
      if (mounted) {
        setState(() {
          isLoading = false;
        });
      }

      //https://blog.csdn.net/yuzhangzhen?code=sTXiae&state=c
      //https://blog.csdn.net/yuzhangzhen?code=ZqJKS0&state=
      if (url != null && url.length > 0 && url.contains("?code=")) {
        String code = url.split("?")[1].split("&")[0].split("=")[1];
        print("code $code");

        Map<String, dynamic> params = {
          "client_id": AppParams.CLIENT_ID,
          "client_secret": AppParams.CLIENT_SECRET,
          "redirect_uri": AppParams.REDIRECT_URI,
          "grant_type": "authorization_code",
          "code": "$code",
          "dataType": "json",
        };

        print("params $params");

        NetUtils.get(AppUrls.OAUTH2_TOKEN, params).then((data) {
          //{
          //   "access_token": "06c6902a-c4e4-443e-b6f8-0fa1292ae792",
          //   "refresh_token": "9d87add9-7d04-4bc5-8e70-104e4d29b120",
          //   "uid": 5170983,
          //   "token_type": "bearer",
          //   "expires_in": 604799
          // }
          print("web:$data");
          if (data != null) {
            //拿到数据
            Map<String, dynamic> map = json.decode(data);
            print("map = $map");
            DataUtils.saveLoginInfo(map);

            //通知界面刷新数据
            Navigator.pop(context, "refresh");
          }
        });
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _flutterWebviewPlugin.close();
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> _appBarTitle = [
      Text(
        "登录开源中国",
        style: TextStyle(
          color: Color(AppColors.APPBAR),
        ),
      ),
    ];

    if (isLoading) {
      _appBarTitle.add(SizedBox(
        width: 10,
      ));

      //加载图表
      _appBarTitle.add(CupertinoActivityIndicator());
    }

    return WebviewScaffold(
      url: _url(),
      appBar: AppBar(
        title: Row(
          children: _appBarTitle,
        ),
      ),
      withJavascript: true,
      //允许执行js
      withLocalStorage: true,
      //允许本地存储
      withZoom: true, //允许缩放
    );
  }

  String _url() {
    var url = AppUrls.OAUTH2_AUTHORIZE +
        "?response_type=code" +
        "&client_id=" +
        AppParams.CLIENT_ID +
        "&client_secret=" +
        AppParams.CLIENT_SECRET +
        "&redirect_uri=" +
        AppParams.REDIRECT_URI;

    print("url = $url");
    //https://www.oschina.net/action/oauth2/authorize?response_type=code&client_id=WoCIqX31djQFGKKxh4o1&client_secret=fPHwvUWSXNWpjELiodaKkpweoiA5TPPE&redirect_uri=https://blog.csdn.net/yuzhangzhen
    return url;
  }
}
